package com.itdd.service.impl;

import com.itdd.mapper.BackMapper;
import com.itdd.mapper.BookMapper;
import com.itdd.mapper.BorrowMapper;
import com.itdd.pojo.Back;
import com.itdd.pojo.Borrow;
import com.itdd.pojo.User;
import com.itdd.service.BackService;
import com.itdd.service.utils.GetSqlSession;
import org.apache.ibatis.session.SqlSession;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

public class BackServiceImpl implements BackService {

    @Override
    public void backBook(User user) {
        SqlSession sqlSession = GetSqlSession.getSqlSession();
        BorrowMapper borrowMapper = sqlSession.getMapper(BorrowMapper.class);
        BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
        BackMapper backMapper = sqlSession.getMapper(BackMapper.class);
        //定义一个输入
        Scanner Sca = new Scanner(System.in);
        while (true) {
            System.out.println("书号\t\t借阅者ID\t\t借阅时间");
            List<Borrow> userBorrows = borrowMapper.selectBorrowByUserId(user.getUserAccount());
            for (int i = 0; i < userBorrows.size(); i++) {
                System.out.println(userBorrows.get(i));
            }
            System.out.println("请输入你要还的书籍");
            System.out.println("如果你想退出，请按0");
            int bId = Sca.nextInt();
            if (bId == 0) break;
//删除借书库中的指定列
            borrowMapper.deleteByBookIdUserAcc(bId, user.getUserAccount());
//还书后书的数量加一
            bookMapper.updateBookNumUp(bId);
//还书库添加数据
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
            Date date = new Date(System.currentTimeMillis());
            backMapper.addBack(bId, user.getUserAccount(), formatter.format(date));
        }
        sqlSession.close();
    }


    @Override
    public void displayBack() {
        SqlSession sqlSession = GetSqlSession.getSqlSession();
        BackMapper backMapper = sqlSession.getMapper(BackMapper.class);
        //定义一个输入
        Scanner Sca = new Scanner(System.in);
        do {
            //全部还书信息
            List<Back> allBack = backMapper.selectAllBack();
            System.out.println("这是全部的还书记录:");
            for (int i = 0; i < allBack.size(); i++) {
                System.out.println(allBack.get(i));
            }
            System.out.println("请输入你要删除的对应还书记录的书号和用户名");
            backMapper.deleteByBookIdUserAcc(Sca.nextInt(), Sca.nextInt());
            System.out.println("删除成功！");
            System.out.println("如果想退出，请按0");
        } while (Sca.nextInt() != 0);
        sqlSession.close();
    }
}
